package mysql

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"golang-sgg-daijia/internal/model"
	"gorm.io/gorm"
)

type DriverAccountDao interface {
	Create(ctx context.Context, driverAccount *model.DriverAccount) error
	UpdateByDriverId(ctx context.Context, driverId int64, driverAccount *model.DriverAccount) (int64,error)
	UpdateByEqCondition(ctx context.Context, driverAccount *model.DriverAccount,
		eqConditions map[string]interface{}) (int64, error)
	GetByDriverId(ctx context.Context, driverId int64) (*model.DriverAccount, error)
}

func NewDriverAccountDao(
	r *MysqlClient,
) DriverAccountDao {
	return &driverAccountDao{
		MysqlClient: r,
	}
}

type driverAccountDao struct {
	*MysqlClient
}

func (r *driverAccountDao) GetByDriverId(ctx context.Context, driverId int64) (*model.DriverAccount, error) {
	driverAccount := &model.DriverAccount{}
	if err := r.DB(ctx).Where("driver_id = ?", driverId).Where("is_deleted", 0).First(driverAccount).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("driverAccountDao|GetByDriverId", zap.Error(err))
		return nil, err
	}
	return driverAccount, nil
}

func (r *driverAccountDao) Create(ctx context.Context, driverAccount *model.DriverAccount) error {
	if err := r.DB(ctx).Create(driverAccount).Error; err != nil {
		r.logger.WithContext(ctx).Error("driverAccountDao|Create(", zap.Any("data", map[string]interface{}{
			"driverSet": *driverAccount,
		}), zap.Error(err))
		return err
	}
	return nil
}

func (r *driverAccountDao) UpdateByDriverId(ctx context.Context, driverId int64, DriverAccount *model.DriverAccount) (int64,error) {
	db := r.DB(ctx).Model(&model.DriverAccount{}).Where("driver_id = ?", driverId).Updates(DriverAccount)
	n, err := db.RowsAffected, db.Error
	if err != nil {
		r.logger.WithContext(ctx).Error("driverAccountDao|UpdateByDriverId(", zap.Any("data", map[string]interface{}{
			"driverId": driverId,
			"DriverAccount": *DriverAccount,
		}), zap.Error(err))
		return 0, err
	}
	return n, nil
}

// UpdateByEqCondition 根据等于条件更新,driverAccount
func (r *driverAccountDao) UpdateByEqCondition(ctx context.Context, driverAccount *model.DriverAccount,
	eqConditions map[string]interface{}) (int64, error) {

	db := r.DB(ctx).Where(eqConditions).Updates(driverAccount)
	n, err := db.RowsAffected, db.Error
	if err != nil {
		r.logger.WithContext(ctx).Error("driverAccount|UpdateByEqCondition", zap.Error(err))
		return 0, err
	}
	return n, nil
}